package com.yan.club.auth.component;

import com.yan.club.auth.model.LoginUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author : 彦
 * @since : 2024/01/26 18:54
 */
@Component("check")
public class MySecurityExpressionRoot {

    public final boolean hasAuthority(String authority) {
        // 获取当前用户的权限
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        List<String> permissions = loginUser.getPermissions();

        if (StringUtils.isEmpty(loginUser) || CollectionUtils.isEmpty(loginUser.getPermissions())) {
            return false;
        }

        // 判断用户权限集合中是否存在authority
        return permissions.contains(authority);
    }
}
